﻿using Microsoft.AspNetCore.Mvc;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class YourTableNameService : IYourTableNameService
    {
        private readonly IBaseRepository<YourTableName> _baseRepository;
        private readonly IBaseRepository<BuildingManagement> management;
        private readonly IBaseRepository<SheepField> sheepfield;
        private readonly IBaseRepository<SheepRecord> record;
        private readonly IBaseRepository<EarTagTable> eartag;
        public YourTableNameService(IBaseRepository<YourTableName> baseRepository, IBaseRepository<BuildingManagement> management, IBaseRepository<SheepField> sheepfield, IBaseRepository<SheepRecord> record, IBaseRepository<EarTagTable> eartag)
        {
            _baseRepository = baseRepository;
            this.management = management;
            this.sheepfield = sheepfield;
            this.record = record;
            this.eartag = eartag;
        }

        /// <summary>
        /// 期初添加
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<int> AddYourTableNames(List<YourTableName> YourTableName)
        {
            foreach (var m in YourTableName)
            {
                var list = eartag.GetAll().FirstOrDefault(s => s.EarTagId ==int.Parse( m.OverBit)).OverBit;
                m.OverBit = list;
                m.ElEarTag = list;
                m.DawningsheepReceipts = YitIdHelper.NextId().ToString();
                m.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
                m.NumbeFelements = 1;
                m.DawningsheepTime = DateTime.Now;
                m.AddTime = DateTime.Now;
                m.AddName = "管理员";
                m.IsDel = 0;
                m.audit = false;
                // 添加 YourTableName 记录
                int result = _baseRepository.Add(m);



                // 如果需要在添加 YourTableName 后添加 SheepRecord 记录，可以这样做：
                if (result > 0)
                {
                    //根据选中的耳号查询
                    var listw = eartag.GetAll().FirstOrDefault(s => s.OverBit == list);
                    //修改耳号状态，（使用的耳号不能再次使用）
                    listw.UseState = 2;
                    eartag.Update(listw);
                    if (m.DawningsheepType == 1)
                    {
                        var sheepRecord = new SheepRecord
                        {
                            // 设置 SheepRecord 的属性
                            // 可以根据需要设置 SheepRecord 的属性，例如关联的 YourTableNameId 等
                            AddName = "管理员",
                            AddTime = DateTime.Now,
                            BuildingName = management.GetAll().FirstOrDefault(x => x.BuildingManagementId == m.BuildingManagementId).BuildingName,
                            DelName = "",
                            DelTime = null,
                            ElEarTag = m.OverBit,
                            IsDel = false,
                            OverBit = m.OverBit,
                            Remarks = "",
                            SheepFieldName = sheepfield.GetAll().FirstOrDefault(x => x.SheepFieldId == m.SheepFieldId).SheepFieldName,
                            SheepRecordBirthDate = null,
                            SheepRecordType = m.DawningsheepType,
                            SheepRecordBirthState = null,
                            SheepRecordBreedDay = null,
                            SheepRecordBreedState = null,
                            SheepRecordDadOverbit = null,
                            SheepRecordDay = null,
                            SheepRecordGene = null,
                            SheepRecordGestation = null,
                            SheepRecordGrowth = null,
                            SheepRecordMarket = null,
                            SheepRecordMomOverbit = null,
                            SheepRecordMoom = null,
                            SheepRecordPresentState = 1,
                            SheepRecordProduction = null,
                            UpdateTime = null,
                            SheepRecordRemark = null,
                            SheepRecordSex = true,

                            SheepRecordVariety = eartag.GetAll().FirstOrDefault(s=>s.OverBit==m.OverBit).BirType,

                            SheepRecordWeaningAge = null,
                            SheepRecordWeaningDate = null,
                            SheepRecordWeaningWeight = null,
                            SheepRecordWeightBirth = null,
                            UpdateName = null,
                            
                        };

                        // 添加 SheepRecord 记录
                        record.Add(sheepRecord);
                    }
                    if (m.DawningsheepType == 2)
                    {
                        var sheepRecord = new SheepRecord
                        {
                            // 设置 SheepRecord 的属性
                            // 可以根据需要设置 SheepRecord 的属性，例如关联的 YourTableNameId 等
                            AddName = "管理员",
                            AddTime = DateTime.Now,
                            BuildingName = management.GetAll().FirstOrDefault(x => x.BuildingManagementId == m.BuildingManagementId).BuildingName,
                            DelName = "",
                            DelTime = null,
                            ElEarTag = m.OverBit,
                            IsDel = false,
                            OverBit = m.OverBit,
                            Remarks = "",
                            SheepFieldName = sheepfield.GetAll().FirstOrDefault(x => x.SheepFieldId == m.SheepFieldId).SheepFieldName,
                            SheepRecordBirthDate = null,
                            SheepRecordType = m.DawningsheepType,
                            SheepRecordBirthState = null,
                            SheepRecordBreedDay = null,
                            SheepRecordBreedState = 1,
                            SheepRecordDadOverbit = null,
                            SheepRecordDay = null,
                            SheepRecordGene = null,
                            SheepRecordGestation = null,
                            SheepRecordGrowth = null,
                            SheepRecordMarket = null,
                            SheepRecordMomOverbit = null,
                            SheepRecordMoom = null,
                            SheepRecordPresentState = 1,
                            SheepRecordProduction = null,
                            UpdateTime = null,
                            SheepRecordRemark = null,
                            SheepRecordSex = false,
                            SheepRecordVariety = eartag.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit).BirType,
                            SheepRecordWeaningAge = null,
                            SheepRecordWeaningDate = null,
                            SheepRecordWeaningWeight = null,
                            SheepRecordWeightBirth = null,
                            UpdateName = null,
                        };

                        // 添加 SheepRecord 记录
                        record.Add(sheepRecord);
                    }
                    if (m.DawningsheepType == 3)
                    {
                        var sheepRecord = new SheepRecord
                        {
                            // 设置 SheepRecord 的属性
                            // 可以根据需要设置 SheepRecord 的属性，例如关联的 YourTableNameId 等
                            AddName = "管理员",
                            AddTime = DateTime.Now,
                            BuildingName = management.GetAll().FirstOrDefault(x => x.BuildingManagementId == m.BuildingManagementId).BuildingName,
                            DelName = "",
                            DelTime = null,
                            ElEarTag = m.OverBit,
                            IsDel = false,
                            OverBit = m.OverBit,
                            Remarks = "",
                            SheepFieldName = sheepfield.GetAll().FirstOrDefault(x => x.SheepFieldId == m.SheepFieldId).SheepFieldName,
                            SheepRecordBirthDate = null,
                            SheepRecordType = m.DawningsheepType,
                            SheepRecordBirthState = null,
                            SheepRecordBreedDay = null,
                            SheepRecordBreedState = null,
                            SheepRecordDadOverbit = null,
                            SheepRecordDay = null,
                            SheepRecordGene = null,
                            SheepRecordGestation = null,
                            SheepRecordGrowth = null,
                            SheepRecordMarket = null,
                            SheepRecordMomOverbit = null,
                            SheepRecordMoom = null,
                            SheepRecordPresentState = 1,
                            SheepRecordProduction = null,
                            UpdateTime = null,
                            SheepRecordRemark = null,
                            SheepRecordSex = null,
                            SheepRecordVariety = eartag.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit).BirType,
                            SheepRecordWeaningAge = null,
                            SheepRecordWeaningDate = null,
                            SheepRecordWeaningWeight = null,
                            SheepRecordWeightBirth = null,
                            UpdateName = null,
                        };

                        // 添加 SheepRecord 记录
                        record.Add(sheepRecord);
                    }

                }
            }
            return 1;
        }

        /// <summary>
        /// 期初显示
        /// </summary>
        /// <returns></returns>

        public async Task<PageOutput<DawningSheepDto>> GetYourTableNames(string? OverBit, int DawningsheepType, int index, int size)
        {
            //var list = _baseRepository.GetAll().Where(s=>s.IsDel==0).ToList();
            //if (!string.IsNullOrWhiteSpace(OverBit))
            //{
            //    list = list.Where(s => s.OverBit.Contains(OverBit)).ToList();
            //}
            //if (DawningsheepType >0)
            //{
            //    list = list.Where(s => s.DawningsheepType == DawningsheepType).ToList();
            //}
            var listDto = (from your in _baseRepository.GetAll()
                           join manage in management.GetAll()
                           on your.BuildingManagementId equals manage.BuildingManagementId
                           join field in sheepfield.GetAll()
                           on your.SheepFieldId equals field.SheepFieldId
                           where your.IsDel == 0
                           && (string.IsNullOrWhiteSpace(OverBit) || your.OverBit.Contains(OverBit))
                           && (DawningsheepType == 0 || your.DawningsheepType == DawningsheepType)
                           select new DawningSheepDto
                           {
                               DawningsheepType = your.DawningsheepType,
                               OverBit = your.OverBit,
                               IsDel = your.IsDel,
                               AddName = your.AddName,
                               AddTime = your.AddTime,
                               audit = your.audit,
                               BuildingManagementId = your.BuildingManagementId,
                               BuildingName = manage.BuildingName,
                               DawningsheepId = your.DawningsheepId,
                               DawningsheepReceipts = your.DawningsheepReceipts,
                               DawningsheepTime = your.DawningsheepTime,
                               DawningsheepWeight = your.DawningsheepWeight,
                               DelName = your.DelName,
                               DelTime = your.DelTime,
                               ElEarTag = your.ElEarTag,
                               NumberOfElements = your.NumberOfElements,
                               PurchaseSerialNumber = your.PurchaseSerialNumber,
                               Remarks = your.Remarks,
                               SheepFieldId = your.SheepFieldId,
                               SheepFieldName = field.SheepFieldName,
                               UpdateName = your.UpdateName,
                               UpdateTime = your.UpdateTime,
                           }).ToList();
            var result = new PageOutput<DawningSheepDto>()
            {
                Total = listDto.Count(),
                PageSize = size,
            };
            var query = listDto.OrderBy(s => s.DawningsheepId).Skip(size * (index - 1)).Take(size).ToList();

            result.Data = query;
            return result;
        }
        /// <summary>
        /// <summary>
        /// 反填
        /// </summary>
        /// <returns></returns>

        public YourTableName backfillYourTableNames(int DawningsheepId)
        {
            return _baseRepository.GetInfoBy(DawningsheepId);
             
        }

        /// <summary>
        /// 修改期初
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<int> UpdateYourTableNames(YourTableName m)
        {
            m.DawningsheepReceipts = YitIdHelper.NextId().ToString();
            m.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
            //m.SheepFieldId = 1;
            m.NumbeFelements = 1;
            m.UpdateTime = DateTime.Now;
            m.UpdateName = "管理员";
            m.IsDel = 0;
            m.audit = false;
            return _baseRepository.Update(m);
        }
        /// <summary>
        /// 单删/批量删除
        /// </summary>
        /// <param name="Idlist"></param>
        /// <returns></returns>
        public async Task<int> DeltetYourTableName(string Idlist)
        {
            if (Idlist.Length < 0)
            {
                return 0;
            }
            var idArray = Idlist.Split(',', StringSplitOptions.RemoveEmptyEntries);
            // 转换为整数数组
            var sheepRecordIds = idArray.Select(id =>
            {
                if (!int.TryParse(id, out int result))
                {
                    throw new ArgumentException($"无效的羊记录ID: {id}");
                }
                return result;
            }).ToList();
            var lists = _baseRepository.GetAll().Where(s => sheepRecordIds.Contains(s.DawningsheepId)).ToList();
            foreach (var item in lists)
            {

                item.IsDel = 1;
                item.UpdateTime = DateTime.Now;
                item.UpdateName = "管理员";
            }
            return _baseRepository.UpdateRange(lists);
        }
        /// <summary>
        /// 单删/批量审核
        /// </summary>
        /// <param name="Idlist"></param>
        /// <returns></returns>
        public async Task<int> AuditYourTableName(string Idlist)
        {
            if (Idlist.Length < 0)
            {
                return 0;
            }
            var idArray = Idlist.Split(',', StringSplitOptions.RemoveEmptyEntries);
            // 转换为整数数组
            var sheepRecordIds = idArray.Select(id =>
            {
                if (!int.TryParse(id, out int result))
                {
                    throw new ArgumentException($"无效的羊记录ID: {id}");
                }
                return result;
            }).ToList();
            var lists = _baseRepository.GetAll().Where(s => sheepRecordIds.Contains(s.DawningsheepId)).ToList();
            foreach (var item in lists)
            {

                item.audit = true;
                item.UpdateTime = DateTime.Now;
                item.UpdateName = "管理员";
            }
            return _baseRepository.UpdateRange(lists);
        }

    }
}


